<template>
  <div class="loginView">
    <div class="loginWrap">
      <a-form
        :model="formState"
        :rules="rules"
        class="loginForm"
        layout="vertical"
        :hideRequiredMark="true"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <h3>用户登录</h3>
        <a-form-item label="账户名" name="username" >
          <a-input class="formInput" v-model:value="formState.username" placeholder="请输入账户名" allow-clear>
          </a-input>
        </a-form-item>

        <a-form-item label="密码" name="password" >
          <a-input-password class="formInput" v-model:value="formState.password" placeholder="请输入密码" allow-clear>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" class="formButton">
            登 录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>


<script lang="ts" setup>
  import { reactive, ref, onBeforeUpdate } from "vue";
  import { useRouter } from 'vue-router';
  import { storeToRefs } from 'pinia'
  import { useUserStore } from '@/store/user';
  import { useRouterStore } from '@/store/router';
  import type { MLoginFormState } from '@/utils/interface';
  import type { Rule } from 'ant-design-vue/es/form';
  import { message } from 'ant-design-vue';
  import { Login } from '@/api/index';
  import { encryptFun } from '@/utils/secret';
  import {normalMixStringReg, passwordReg } from '@/utils/validate';

  const router = useRouter();
  const userStore = useUserStore();
  const routerStore = useRouterStore();
  const { userId, username, type, tokenHeaderName, tokenValue } = storeToRefs(userStore);
  const { activeRouteItem, routeList } = storeToRefs(routerStore);
  const formState = reactive<MLoginFormState>({
    username: '',
    password: '',
  });

  const validateName = async (_rule: Rule, value: string) => {
    if (value === '') {
      return Promise.reject('请输入账户名');
    } else {
      if (!normalMixStringReg.test(value)) {
        return Promise.reject('必须为数字、英文、汉字或特殊符号的组合,1~20位');
      } else {
        return Promise.resolve();
      }
    }
  };

  const validatePass = async (_rule: Rule, value: string) => {
    console.log(value);
    if (value === '') {
      return Promise.reject('请输入密码');
    } else {
      if (!passwordReg.test(value)) {
        return Promise.reject('至少包含数字、字母、特殊符号中的两种,6~20位');
      } else {
        return Promise.resolve();
      }
    }
  };

  const rules: Record<string, Rule[]> = {
    username: [{ required: true, validator: validateName, trigger: 'blur' }],
    password: [{ required: true, validator: validatePass, trigger: 'blur' }],
  };
  
  onBeforeUpdate(() => {
    formState.username = "";
    formState.password = "";
  });

  const onFinish = async (values: any) => {
    const pwd = await encryptFun(values.password);
    const res = await Login({
      username: values.username,
      password: pwd,
    })
    if(res) {
      if(res.code === 1000) {
        type.value = res.data.type;
        userId.value = res.data.userId;
        username.value = res.data.username;
        tokenValue.value = res.data.tokenValue;
        tokenHeaderName.value = res.data.tokenHeaderName;
        activeRouteItem.value = routeList.value[0].children![0];
        router.push({path: routeList.value[0].children![0].path});
      } else {
        message.error(res.msg);
      }
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
</script>

<style lang="scss" scoped>
.loginView {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  background: url("@/assets/images/loginBg.png") no-repeat;
  background-size: cover;
  .loginWrap {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;     /* 垂直居中 */
    height: 100vh; 
    .loginForm {
      position: fixed;
      left: 50%;
      top: 45%;
      transform: translate(-50%, -50%);
      border-radius: 10px;
      width: 450px;
      padding: 80px;;
      text-align: left;
      background: rgba(255, 255, 255, 0.3);
      box-shadow: 0px 19px 39px  rgba(222, 225, 255, 1);
      backdrop-filter: blur(20px);
      h3 {
        font-size: 2em;
        font-weight: bold;
        margin: 0 auto 40px;
        text-align: left;
        color: rgba(42, 30, 23, 1);
      }
      ::v-deep .ant-form-item {
        margin-bottom: 14px;
      }
      .formInput {
        height: 42px;
        line-height: 42px;
        ::v-deep input {
          background-color: #F5F7FF!important
        }
      }
      .codeDiv {
        .formInput{
          width: calc(100% - 100px);
          float: left;
          border-radius: 6px 0 0 6px
        }
        .code{
          width: 100px;
          height: 42px;
          text-align: center;
          line-height: 42px;
          border-left: none;
          cursor: pointer;
          background: #494949;
          margin-left: calc(100% - 100px);
          overflow: hidden;
        }
      }
      .formButton {
        width: 100%;
        height: 42px;
        line-height: 42px;
        padding: 0;
        margin-top: 40px;
        background-color: #4487EC;
      }
    }
  }
}
</style>